package com.project.erp.action.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.project.erp.action.BaseAction;
import com.project.erp.common.Constants;
import com.project.erp.common.utils.CookieUtil;
import com.project.erp.common.utils.I18nUtils;
import com.project.erp.common.utils.Page;
import com.project.erp.common.utils.encode.EncodeUtils;
import com.project.erp.common.utils.encode.JsonBinder;
import com.project.erp.common.utils.encode.MD5Util;
import com.project.erp.model.system.Privilege;
import com.project.erp.model.system.Role;
import com.project.erp.model.system.User;
import com.project.erp.service.system.PrivilegeService;
import com.project.erp.service.system.RoleService;
import com.project.erp.service.system.UserService;

@Controller
@Scope("prototype")
public class UserAction extends BaseAction implements ModelDriven<User>{

	private static final long serialVersionUID = -607468359983436553L;
	
	@Autowired
	private PrivilegeService privilegeService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	private User user;
	
	private List<Privilege> privileges;
	
	private List<Long> roleIds;
	
	private String userIds;
	
	private String checkRoleIds;
	
	private String uncheckRoleIds;
	
	@SuppressWarnings("unchecked")
	public String toMain() throws Exception {
		logger.info("entry toMain ...");
		try{
			//所有的菜单信息
			List<Privilege> privilegeList = (List<Privilege>)getSession().getAttribute(Constants.ERP_CURRENT_USER_RIGHTCODES);
			privileges = new ArrayList<Privilege>();
			for (Privilege privilege : privilegeList) { 
				if(null == privilege.getParentId()){
					privileges.add(privilege);
				}
				//设置role为空,否则json序列化出错
				privilege.setRoles(null);
			}
			getRequest().setAttribute("privileges", privileges);
		}catch(Exception e){
			logger.error("execute toMain error!", e);
		}
		return SUCCESS;
	}
	
	@Override
	public String execute() throws Exception {
		logger.info("entry listUser method ...");
		return SUCCESS;
	}

	public String getUserListData() throws Exception{
		logger.debug("entry getUserListData method ...");
		try{
			Page<User> page = new Page<User>();
			page.setPageNo(getPage());
			page.setPageSize(getRows());
			page.setOrderBy("createTime");
			page.setOrder(Page.DESC);
			page = userService.getUserPageBySearch(page, user);
			//设置Role为空,不加载角色信息
			for (User acctUser : page.getResult()) {
				acctUser.setRoleList(new ArrayList<Role>());
			}
			//设置表格返回数据
			this.getResultMap().put("total", page.getTotalCount());
			this.getResultMap().put("rows", page.getResult());
		}catch(Exception e){
			logger.error("execute getUserListData error!", e);
		}
		return SUCCESS;
	}
	
	public String toLogin() throws Exception{
		//设置用户默认语言、地区
		I18nUtils.setDefaultLocale(getSession());
		return SUCCESS;
	}
	
	/**
	 * 登录 先检查用户名是否存在，再检查用户名和密码是否相符
	 * @return 登录成功 SUCCESS 用户名不存在 NONE 密码不符 INPUT
	 * @throws Exception
	 */
	public String login() throws Exception {
		logger.debug("entry Login method ...");
		try {
			
			//先判断验证码是否正常
			if(!user.getRandCheckCode().equalsIgnoreCase((String)getSession().getAttribute(Constants.RAND_CHECK_CODE))){
				this.getResultMap().put("resultType", "checkCode");
				return SUCCESS;
			}
			
			User loginUser = userService.getUserByUserName(user.getLoginName());
			String loginName = user.getLoginName();
			if(null != loginUser && StringUtils.isNotBlank(loginName)){
				if(loginUser.getPassword().equals(MD5Util.getMD5String(user.getPassword()))){
					
					String cookieValue = Constants.WEB_COOKIE_KEY + Constants.WEB_COOKIE_SPLIT + loginUser.getLoginName() + Constants.WEB_COOKIE_SPLIT + loginUser.getPassword();
					String cookieValueBase64 = EncodeUtils.base64Encode(cookieValue.getBytes());
					CookieUtil.setCookie(getRequest(), getResponse(), Constants.ERP_COOKIE_CURRENT_KEY, cookieValueBase64, Constants.ERP_COOKIE_MAX_AGE);
					//存放用户信息
					getSession().setAttribute(Constants.ERP_CURRENT_USER, loginUser);
					//根据角色获取所有的菜单信息
					List<Privilege> privilegeList = privilegeService.getPrivilegeByRoles(loginUser.getRoleList());
					//存放用户权限码信息
					getSession().setAttribute(Constants.ERP_CURRENT_USER_RIGHTCODES, privilegeList);
					this.getResultMap().put("resultType", "success");
				}else{
					this.getResultMap().put("resultType", "input");
				}
			}else{
				this.getResultMap().put("resultType", "none");
			}
		} catch (Exception e) {
			logger.error("execute login page error!", e);
		}
		
		return SUCCESS;
	}
	
	public String logout() throws Exception {
		logger.debug("entry logout method ...");
		try {
			
			CookieUtil.deleteCookie(getRequest(), getResponse(), CookieUtil.getCookie(getRequest(), Constants.ERP_COOKIE_CURRENT_KEY));
			getSession().removeAttribute(Constants.RAND_CHECK_CODE);
			getSession().removeAttribute(Constants.ERP_CURRENT_USER);
			getSession().removeAttribute(Constants.ERP_CURRENT_USER_RIGHTCODES);
			//session注销
			getSession().invalidate();
		} catch (Exception e) {
			logger.error("execute logout page error!", e);
		}
		return SUCCESS;
	}

	/**
	 * 到添加用户页面
	 * @return SUCCESS
	 * @throws Exception 异常处理
	 */
	public String toAddUser() throws Exception{
		logger.debug("entry toAddUser method!...");
		try{
			//获取所有角色列表数据
			List<Role> roleList = roleService.getAllRoles();
			getRequest().setAttribute("roleList", roleList);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("execute toAddUser page error!", e);
		}
		return SUCCESS;
	}
	
	/**
	 * 保存用户信息
	 * @return SUCCESS
	 * @throws Exception 异常信息
	 */
	public String addUser() throws Exception{
		logger.debug("entry addUser method!...");
		try{
			if(null != this.roleIds){
				List<Role> roleList = new ArrayList<Role>();
				Role role = null;
				for (Long roleId : roleIds) {
					role = new Role();
					role.setId(roleId);
					roleList.add(role);
				}
				user.setRoleList(roleList);
			}
			//设置密码加密
			user.setPassword(MD5Util.getMD5String(user.getPassword()));
			userService.saveUser(user);
			//返回成功信息
			this.getResultMap().put("result", SUCCESS);
			this.getResultMap().put("msg","添加用户信息成功");
		}catch(Exception e){
			//返回错误信息
			logger.error("添加用户信息失败,失败原因:" + e.getMessage(),e);
			this.getResultMap().put("result",ERROR);
			this.getResultMap().put("msg","添加用户信息失败");
		}
		return SUCCESS;
	}
	
	/**
	 * 到修改用户页面
	 * @return SUCCESS
	 * @throws Exception 异常处理
	 */
	public String toEditUser() throws Exception{
		logger.debug("entry toEditUser method!...");
		try{
			logger.info("********************userId="+user.getId());
			Long userId = user.getId();
			user = userService.getUserById(userId);
			//用户所属角色列表信息(转化成Map数据)
			Map<Long,Role> roleMap = new HashMap<Long,Role>();
			if(null != user.getRoleList()){
				for (Role acctRole : user.getRoleList()) {
					roleMap.put(acctRole.getId(), acctRole);
				}
			}
			//获取所有角色列表数据
			List<Role> roleList = roleService.getAllRoles();
			for (Role acctRole : roleList) {
				if(null != roleMap.get(acctRole.getId())){
					acctRole.setCheckFlag(true);
				}
			}
			getRequest().setAttribute("roleList", roleList);
		}catch(Exception e){
			//e.printStackTrace();
			logger.error("execute toEditUser page error!", e);
		}
		return SUCCESS;
	}
	
	/**
	 * 修改用户信息
	 * @return
	 * @throws Exception
	 */
	public String editUser() throws Exception{
		logger.debug("entry editUser method!...");
		try{
			logger.info("user="+user);
			User persistentUser = userService.getUserById(user.getId());
			/*List<Role> roleList = new ArrayList<Role>();
			if(null != persistentUser.getRoleList() && persistentUser.getRoleList().size() > 0){
				for (Role role : persistentUser.getRoleList()) {
					roleList.add(role);
				}
			}*/
			user.setRoleList(persistentUser.getRoleList());
			//注:创建日期在这拷贝为空覆盖以前的,所有不拷贝创建日期
			BeanUtils.copyProperties(user, persistentUser, new String[]{"password","createTime"});
			//修改用户信息
			userService.editUser(persistentUser);
			//返回成功信息
			this.getResultMap().put("result", SUCCESS);
			this.getResultMap().put("msg", "修改用户信息成功");
		}catch(Exception e){
			//返回错误信息
			logger.error("修改用户信息失败,失败原因:" + e.getMessage(),e);
			this.getResultMap().put("result",ERROR);
			this.getResultMap().put("msg", "修改用户信息失败");
		}
		return SUCCESS;
	}
	
	/**
	 * 分配角色页面
	 * @return success
	 * @throws Exception exception
	 */
	public String toAssignRoles() throws Exception{
		logger.debug("entry toAssignRoles method!...");
		try{
			user = userService.getUserById(user.getId());
			List<Role> roleList = new ArrayList<Role>();
			for (Role role : user.getRoleList()) {
				role.setPrivileges(null);
				roleList.add(role);
			}
			String rolesJson = JsonBinder.buildNormalBinder().toJson(roleList);
			getRequest().setAttribute("roleList",rolesJson);
		}catch(Exception e){
			//返回错误信息
			logger.error("进入分配角色失败:" + e.getMessage(),e);
		}
		return SUCCESS;
	}
	
	/**
	 * 分配角色处理方法
	 * @return success
	 * @throws Exception exception
	 */
	public String assignRoles() throws Exception{
		logger.debug("entry assignRoles method!...");
		try{
			user = userService.getUserById(user.getId());
			List<Role> roleList = user.getRoleList();
			Map<Long,Role> roleIdMap = new HashMap<Long,Role>();
			for (Role role : roleList) {
				roleIdMap.put(role.getId(), role);
			}
			//处理选中角色的情况
			if(StringUtils.isNotEmpty(checkRoleIds)){
				String[] roleIds = checkRoleIds.split(",");
				if(null != roleList && roleList.size() > 0){
					boolean falg = true;
					Role r = null;
					for(String roleId:roleIds){
						if(!roleIdMap.containsKey(Long.valueOf(roleId))){
							falg = false;
							r = new Role();
							r.setId(Long.valueOf(roleId));
							roleList.add(r);
						}
					}
					if(falg){
						//不需要保存数据库信息
						return SUCCESS;
					}
				}else{
					roleList = new ArrayList<Role>();
					Role r = null;
					for(String roleId:roleIds){
						r = new Role();
						r.setId(Long.valueOf(roleId));
						roleList.add(r);
					}
				}
			}
			//处理取消选中角色的情况
			if(StringUtils.isNotEmpty(uncheckRoleIds)){
				String[] roleIds = uncheckRoleIds.split(",");
				for(String roleId:roleIds){
					if(roleIdMap.containsKey(Long.valueOf(roleId))){
						roleList.remove(roleIdMap.get(Long.valueOf(roleId)));
					}
				}
			}
			user.setRoleList(roleList);
			userService.editUser(user);
		}catch(Exception e){
			//返回错误信息
			logger.error("entry assignRoles method exception:" + e.getMessage(),e);
		}
		return SUCCESS;
	}
	
	public String checkLoginName() throws Exception{
		logger.debug("entry checkLoginName method!...");
		try{
			this.getResultMap().put("checkFlag",true);
			if(StringUtils.isNotBlank(user.getLoginName())){
				User u = userService.getUserByUserName(user.getLoginName());
				if(null != u){
					this.getResultMap().put("checkFlag",false);
				}
			}
		}catch(Exception e){
			//返回错误信息
			logger.error("entry checkLoginName method exception:" + e.getMessage(),e);
			this.getResultMap().put("result",ERROR);
		}
		this.getResultMap().put("result",SUCCESS);
		return SUCCESS;
	}
	/**
	 * 删除用户信息
	 * @return
	 * @throws Exception
	 */
	public String delUser() throws Exception{
		logger.debug("entry delUser method!...");
		try{
			logger.info("userIds="+userIds);
			String[] arrayIds = userIds.split(",");
			userService.delUser(arrayIds);
			//返回成功信息
			this.getResultMap().put("result", SUCCESS);
			this.getResultMap().put("msg", "删除用户成功");
		}catch(Exception e){
			//返回错误信息
			e.printStackTrace();
			this.getResultMap().put("result",ERROR);
			this.getResultMap().put("msg", "删除用户失败");
		}
		return SUCCESS;
	}
	
	public List<Privilege> getPrivileges() {
		return privileges;
	}

	public void setPrivileges(List<Privilege> privileges) {
		this.privileges = privileges;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public User getModel() {
		if(null == user){
			user = new User();
		}
		return user;
	}

	public List<Long> getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(List<Long> roleIds) {
		this.roleIds = roleIds;
	}

	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	public String getCheckRoleIds() {
		return checkRoleIds;
	}

	public void setCheckRoleIds(String checkRoleIds) {
		this.checkRoleIds = checkRoleIds;
	}

	public String getUncheckRoleIds() {
		return uncheckRoleIds;
	}

	public void setUncheckRoleIds(String uncheckRoleIds) {
		this.uncheckRoleIds = uncheckRoleIds;
	}
	
}
